package com.smalljj.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.smalljj.comm.Constants;
import com.smalljj.comm.Util;

public class IndexActivity extends Activity {

	private EditText userName, password;
	private CheckBox rem_pw, auto_login;
	private Button btn_login;
	private ImageButton btnQuit;
	private String userNameValue, passwordValue;
	private SharedPreferences sp;
	//post form
	HttpPost httpRequest=null; 
    List <NameValuePair> params=null; 
    HttpResponse httpResponse; 

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去除标题
		setContentView(R.layout.index);

		// 获取系统的连接服务
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		// 无网络
		if (connectivity.getActiveNetworkInfo() == null) {
			noNetworkDialog();
			return;
		} else {
			NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
			if (networkInfo == null || networkInfo.isAvailable() == false) {
				noNetworkDialog();
				return;
			}
		}
		// 检查新版本
		CheckVersionTask checkVersionTask = new CheckVersionTask();
		checkVersionTask.execute();

		// 获得实例对象
		sp = this.getSharedPreferences("SMALLJJ", Context.MODE_PRIVATE);//不用MODE_WORLD_READABLE
		userName = (EditText) findViewById(R.id.et_zh);
		password = (EditText) findViewById(R.id.et_mima);
		rem_pw = (CheckBox) findViewById(R.id.cb_mima);
		auto_login = (CheckBox) findViewById(R.id.cb_auto);
		btn_login = (Button) findViewById(R.id.btn_login);
		btnQuit = (ImageButton) findViewById(R.id.img_btn);

		// 判断记住密码多选框的状态
		if (sp.getBoolean("ISCHECK", false)) {
			// 设置默认是记录密码状态
			rem_pw.setChecked(true);
			userName.setText(sp.getString("USERNAME", ""));
			password.setText(sp.getString("PASSWORD", ""));
			// 判断自动登陆多选框状态
			if (sp.getBoolean("AUTO_ISCHECK", false)) {
				// 设置默认是自动登录状态
				auto_login.setChecked(true);
				// 跳转界面
				Intent intent = new Intent(IndexActivity.this,
						LoginActivity.class);
				IndexActivity.this.startActivity(intent);

			}
		}

		// 登录监听事件
		btn_login.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				LoginTask loginTask = new LoginTask();
				loginTask.execute();				
			}
		});

		// 监听记住密码多选框按钮事件
		rem_pw.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (rem_pw.isChecked()) {
					sp.edit().putBoolean("ISCHECK", true).commit();
				} else {
					sp.edit().putBoolean("ISCHECK", false).commit();
				}
			}
		});

		// 监听自动登录多选框事件
		auto_login.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (auto_login.isChecked()) {
					System.out.println("自动登录已选中");
					sp.edit().putBoolean("AUTO_ISCHECK", true).commit();
				} else {
					System.out.println("自动登录没有选中");
					sp.edit().putBoolean("AUTO_ISCHECK", false).commit();
				}
			}
		});

		btnQuit.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				IndexActivity.this.finish();
			}
		});
	}

	/**
	 * 无网络
	 */
	private void noNetworkDialog() {
		Dialog dialog = new AlertDialog.Builder(IndexActivity.this)
			.setTitle("注意").setMessage("当前网络不可用,请检查网络!")
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();// 关闭对话框
					IndexActivity.this.finish();// 结束Activity
				}
			}).create();
		dialog.show();
	}

	/**
	 * 新版本
	 */
	private void newVersionDialog(final String newVersion) {
		new AlertDialog.Builder(IndexActivity.this)
		.setTitle("提示")
		.setMessage("检测到新版本,建议更新使用!")
		.setPositiveButton("更新", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();// 关闭对话框
				// 切换到更新activity
				Bundle bundle = new Bundle();
				bundle.putString("newVersion", newVersion);// 把这个版本号传到UpdateActivity
				Intent intent = new Intent(IndexActivity.this,
						UpdateActivity.class);
				intent.putExtras(bundle);
				IndexActivity.this.startActivity(intent);
				IndexActivity.this.finish();
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).create().show();
	}

	/**
	 * 检测版本更新
	 * 
	 */
	class CheckVersionTask extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... params) {
			return Util.checkNewVersion();
		}

		@Override
		protected void onPostExecute(String result) {
			if (result.equals("") == false) {
				newVersionDialog(result);
				return;
			}
		}
	}

	/**
	 * 登录
	 * 
	 */
	class LoginTask extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... paras) {
			userNameValue = userName.getText().toString();
			passwordValue = password.getText().toString();
			String username = Base64.encodeToString( userNameValue.getBytes(),Base64.DEFAULT);
			String password = Base64.encodeToString( passwordValue.getBytes(),Base64.DEFAULT);
			
			//post 提交登录表单
	        httpRequest=new HttpPost(Constants.ANDROID_WEB+"/user/login"); 
	        /*Post运作传送变数必须用NameValuePair[]阵列储存*/ 
	        params=new ArrayList<NameValuePair>(); 
	        params.add(new BasicNameValuePair("username",username));
	        params.add(new BasicNameValuePair("password",password));
	        try { 
	            //发出HTTP request 
	            httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); 
	            //取得HTTP response 
	            httpResponse=new DefaultHttpClient().execute(httpRequest); 
	            //若状态码为200
	            if(httpResponse.getStatusLine().getStatusCode()==200){ 
	                //取出回应字串 
	                String strResult=EntityUtils.toString(httpResponse.getEntity()); 
	                return strResult;
                }else{
                	Toast.makeText(IndexActivity.this, "未知错误!" , Toast.LENGTH_LONG).show();
                }
	        }catch (Exception e) {
	        	Toast.makeText(IndexActivity.this, "未知错误!", Toast.LENGTH_LONG).show();
			}
			return "";
		}
		@Override
		protected void onPostExecute(String result) {
			try {
				JSONObject jsonObject = new JSONObject(result);
	            String jsonResult = jsonObject.getString("result");
	            String jsonMessage = jsonObject.getString("message");
	            if(jsonResult.equalsIgnoreCase("true")){
	            	Toast.makeText(IndexActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
					Editor editor = sp.edit();
					editor.putString("USERID", jsonObject.getString("userid"));
	            	// 登录成功和记住密码框为选中状态才保存用户信息
					if (rem_pw.isChecked()) {
						// 记住用户名、密码
						editor.putString("USERNAME", userNameValue);
						editor.putString("PASSWORD", passwordValue);
					}
					editor.commit();
					
	            }else{
                	Toast.makeText(IndexActivity.this, jsonMessage , Toast.LENGTH_LONG).show();
	            }
			} catch (Exception e) {
				Toast.makeText(IndexActivity.this, "未知错误!", Toast.LENGTH_LONG).show();
			}
		}
	}
}